package com.qianniu.napi.admin.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.Jinfo;
import com.qianniu.napi.admin.entity.MerchantApp;
import com.qianniu.napi.admin.entity.User;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.ShellUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author chenxuebin
 * @since 2017-02-24
 */
@Controller
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private IUserService userService;
    @Autowired
    private IRedisService redisService;
    @Autowired
    private IJifenService jifenService;
    @Autowired
    private IStoreService storeService;
    @Autowired
    private IMerchantAppService merchantappService;

    @RequestMapping("admin/user/index")
    public String index(Model model) {

        logger.info("========ObjectUtil.getIsAdmin()=" + ObjectUtil.getIsAdmin());
        if (ObjectUtil.getIsAdmin() == 1) {
            Wrapper<MerchantApp> wrapper = new EntityWrapper<MerchantApp>().setSqlSelect("id,name").ne("id", 3);
            List<MerchantApp> list = merchantappService.selectList(wrapper);
            model.addAttribute("isAdmin", 1);
            model.addAttribute("ulist", list);
        } else {
            Wrapper<MerchantApp> wrapper = new EntityWrapper<MerchantApp>().setSqlSelect("id,name").eq("mid", ObjectUtil.getMid()).ne("id", 3);
            List<MerchantApp> list = merchantappService.selectList(wrapper);
            model.addAttribute("isAdmin", 0);
            model.addAttribute("ulist", list);
        }
        return "admin/user";
    }

    @RequestMapping("/admin/user/list")
    @ResponseBody
    public Page<User> list(@RequestParam(value = "search", required = false) String search,
                           @RequestParam(value = "status", required = false) String mpid,
                           @RequestParam(value = "limit", required = false) int limit,
                           @RequestParam(value = "offset", required = false) int offset) {
        Wrapper<User> wrapper = new EntityWrapper<User>();
        int utype = ObjectUtil.getUserType();
        if (utype < 39)
            wrapper.eq("mpid", ObjectUtil.getMpid());
        else if (utype < 99)
            wrapper.eq("mid", ObjectUtil.getMid());

        if (!Strings.isNullOrEmpty(mpid)) {
            wrapper.eq("mpid", mpid);
        }
        if (!Strings.isNullOrEmpty(search)) {
            wrapper.andNew().like("nick_name", search).or().like("phone", search);
        }

        wrapper.isNotNull("openid").orderBy("id", false);

        Page<User> page = userService.selectPage(new Page<User>(offset / limit + 1, limit), wrapper);
        return page;
    }

    @RequestMapping("/admin/user/add")
    public String add(@Valid User bean, BindingResult bindingResult, Model model) {
        // 字段校验
        if (bindingResult.hasErrors()) {
            logger.debug("There are errors! {}", bindingResult);
            return null;
        }
        bean.setCreatetime(new Date());
        bean.setMid(ObjectUtil.getMid());
        bean.insert();
        if (ObjectUtil.getIsAdmin() == 1) {
            Wrapper<MerchantApp> wrapper = new EntityWrapper<MerchantApp>().setSqlSelect("id,name");
            List<MerchantApp> list = merchantappService.selectList(wrapper);
            model.addAttribute("isAdmin", ObjectUtil.getIsAdmin());
            model.addAttribute("list", list);
        }
        return "admin/user";
    }

    @RequestMapping("/admin/user/setMuserAdmin")
    @ResponseBody
    public Jinfo setMuserAdmin(String id, String phone, String mpid) {
        Jinfo json = new Jinfo();
        logger.info("======/admin/user/setMuserAdmin");
        logger.info("======id=" + id);
        logger.info("======phone=" + phone);
        logger.info("======mpid=" + mpid);

        User user = userService.selectById(id);
        if (Strings.isNullOrEmpty(phone) || phone.length() != 11) {
            json.setCode(1);
            json.setMsg("输入手机号有误");
            return json;
        }
        if (user.getMid().toString() != mpid) {
            json.setCode(4);
            json.setMsg("找不到该用户");
            return json;
        }
        user.setPhone(phone);
        user.setIsPlatform(1);
        user.setIsAdmin(1);
        user.setIsMch(-1);
        user.updateById();
        redisService.delUser(user.getId());

        return json;
    }

    @RequestMapping("/admin/user/setadminphone")
    @ResponseBody
    public Jinfo setadminphone(String id, String phone) {
        Jinfo json = new Jinfo();
        logger.info("======/admin/user/setMuserAdmin");
        logger.info("======id=" + id);
        logger.info("======phone=" + phone);

        User user = userService.selectOne(new EntityWrapper<User>()
                .setSqlSelect("id,phone,mid")
                .eq("id", id));
        if (Strings.isNullOrEmpty(phone) || phone.length() != 11) {
            json.setCode(1);
            json.setMsg("输入手机号有误");
            return json;
        }
        user.setPhone(phone);
        user.updateById();
        redisService.delUser(user.getId());

        return json;
    }

    @RequestMapping("/admin/user/getUserById")
    @ResponseBody
    public User getUserById(long id) {
        User user = userService.selectById(id);
        return user;
    }

    @RequestMapping("/admin/user/deleteOne")
    @ResponseBody
    public int deleteOne(long id) {
        boolean isSucc = userService.deleteById(id);
        return isSucc ? 1 : 0;
    }

    @RequestMapping("/admin/user/changeState")
    @ResponseBody
    public String changeState(long id, int state) {
        User bean = new User();
        bean.setId(id);
        bean.setState(state);
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        userService.updateById(bean);
        return "success";
    }

    @RequestMapping("/admin/user/modify")
    public String update(User bean) {
        bean.setModifytime(new Date());
        bean.setModifier(ObjectUtil.getUid());
        boolean isSuccc = userService.updateById(bean);
        if (isSuccc) {
            return "redirect:index";
        }
        return "error";
    }

    @RequestMapping("/admin/user/yasuonav")
    @ResponseBody
    public Jinfo yasuonav(long id, int state) {
        Jinfo info = new Jinfo();
        List<String> navs = new ArrayList<String>();
        List<String> navsto = new ArrayList<String>();
        navs.add("/fafa/www/images/admin/resource/qiche.png");
        navsto.add("/fafa/www/images/admin/resource/new/qiche.png");

        navs.add("/fafa/www/images/admin/resource/canyin.png");
        navsto.add("/fafa/www/images/admin/resource/new/canyin.png");

        navs.add("/fafa/www/images/admin/resource/shuma.png");
        navsto.add("/fafa/www/images/admin/resource/new/shuma.png");

        navs.add("/fafa/www/images/admin/resource/xiuxiandujia.png");
        navsto.add("/fafa/www/images/admin/resource/new/xiuxiandujia.png");

        navs.add("/fafa/www/images/admin/resource/lvyou.png");
        navsto.add("/fafa/www/images/admin/resource/new/lvyou.png");

        navs.add("/fafa/www/images/admin/resource/wentiyongpin.png");
        navsto.add("/fafa/www/images/admin/resource/new/wentiyongpin.png");

        navs.add("/fafa/www/images/admin/resource/meirong.png");
        navsto.add("/fafa/www/images/admin/resource/new/meirong.png");

        navs.add("/fafa/www/images/admin/resource/hunshasheying.png");
        navsto.add("/fafa/www/images/admin/resource/new/hunshasheying.png");

        navs.add("/fafa/www/images/admin/resource/jiancai.png");
        navsto.add("/fafa/www/images/admin/resource/new/jiancai.png");

        navs.add("/fafa/www/images/admin/resource/fangwuzhongjie.png");
        navsto.add("/fafa/www/images/admin/resource/new/fangwuzhongjie.png");

        navs.add("/fafa/www/images/admin/resource/shangchao.png");
        navsto.add("/fafa/www/images/admin/resource/new/shangchao.png");

        navs.add("/fafa/www/images/admin/resource/fuzhuang.png");
        navsto.add("/fafa/www/images/admin/resource/new/fuzhuang.png");

        navs.add("/fafa/www/images/admin/resource/jiucha.png");
        navsto.add("/fafa/www/images/admin/resource/new/jiucha.png");

        navs.add("/fafa/www/images/admin/resource/zhaopinqiuzhi.png");
        navsto.add("/fafa/www/images/admin/resource/new/zhaopinqiuzhi.png");

        navs.add("/fafa/www/images/admin/resource/zhuangshi.png");
        navsto.add("/fafa/www/images/admin/resource/new/zhuangshi.png");

        navs.add("/fafa/www/images/admin/resource/jianshen.png");
        navsto.add("/fafa/www/images/admin/resource/new/jianshen.png");

        navs.add("/fafa/www/images/admin/resource/jiaoyupeixun.png");
        navsto.add("/fafa/www/images/admin/resource/new/jiaoyupeixun.png");

        navs.add("/fafa/www/images/admin/resource/zhubao.png");
        navsto.add("/fafa/www/images/admin/resource/new/zhubao.png");

        navs.add("/fafa/www/images/admin/resource/shuiguoshengxian.png");
        navsto.add("/fafa/www/images/admin/resource/new/shuiguoshengxian.png");

        navs.add("/fafa/www/images/admin/resource/sirendingzhi.png");
        navsto.add("/fafa/www/images/admin/resource/new/sirendingzhi.png");

        navs.add("/fafa/www/images/admin/resource/zihneng.png");
        navsto.add("/fafa/www/images/admin/resource/new/zihneng.png");

        navs.add("/fafa/www/images/admin/resource/gongxiangguangga.png");
        navsto.add("/fafa/www/images/admin/resource/new/gongxiangguangga.png");

        navs.add("/fafa/www/images/admin/resource/shenghuo.png");
        navsto.add("/fafa/www/images/admin/resource/new/shenghuo.png");

        navs.add("/fafa/www/images/admin/resource/muying.png");
        navsto.add("/fafa/www/images/admin/resource/new/muying.png");

        navs.add("/fafa/www/images/admin/resource/baojianshangpin.png");
        navsto.add("/fafa/www/images/admin/resource/new/baojianshangpin.png");

        navs.add("/fafa/www/images/admin/resource/lvsenongpin.png");
        navsto.add("/fafa/www/images/admin/resource/new/lvsenongpin.png");

        navs.add("/fafa/www/images/admin/resource/shenghuoyongpin.png");
        navsto.add("/fafa/www/images/admin/resource/new/shenghuoyongpin.png");

        navs.add("/fafa/www/images/admin/resource/shangwu.png");
        navsto.add("/fafa/www/images/admin/resource/new/shangwu.png");

        navs.add("/fafa/www/images/admin/resource/tesefuwu.png");
        navsto.add("/fafa/www/images/admin/resource/new/tesefuwu.png");

        navs.add("/fafa/www/images/meikeduoduo/navs/shangcheng.png");
        navsto.add("/fafa/www/images/admin/resource/new/shangcheng.png");

        navs.add("/fafa/www/images/meikeduoduo/navs/jiaoliu.png");
        navsto.add("/fafa/www/images/admin/resource/new/jiaoliu.png");

        for (int i = 0; i < navs.size(); i++) {
            try {
                Thumbnails.of(navs.get(i)).size(100, 100).toFile(navsto.get(i));
                ShellUtil.execShell("mv "+navs.get(i)+" /fafa/www/images/admin/resource/old/");
                ShellUtil.execShell("mv "+navsto.get(i)+" /fafa/www/images/admin/resource/");
            } catch (Exception e) {
                logger.error("yasuonav error",e);
            }
        }
        return info;
    }

}
